
    var $ = layui.jquery
        ,form = layui.form
        ,laydate=layui.laydate
        ,upload = layui.upload
        ,table=layui.table
        ,usercode=getQueryVariable("usercode")
        ,dcode=getQueryVariable("dcode")
        ,data=""
        ,userid=""
        ,topbase=getQueryVariable("topbase")
        ,tableIds=new Array()
        ,ids=new Array()
        ,logDBList=[]//日志
        ;
    //当前编号
    let userDepartmentCode;

    //用户组
    let userRoleList = [];
    //角色 多选框对象
    let rolesTreeList=[];
    function getAllJson(jsons) {
        let tmpitem=[]
        for (let item of jsons) {
            let tmparr={}
            tmparr["value"]=item["code"];
            tmparr["name"]=item["name"];
            if(!isEmpty(userRoleList)){
                if(checkIsContain(userRoleList, item["code"])){
                    tmparr["selected"]=true;
                }
            }
            if(item["users"]){
                for(let it of item["users"]){
                    item["list"].push(it)
                }
            }
            if(item["list"] && item["list"].length){
                tmparr["children"]=   this.getAllJson(item["list"]);
                tmpitem.push(tmparr)
            }else{
                tmpitem.push(tmparr)
            }

        }
        return tmpitem
    }

    function getxmselect(el,name, data) {
        return xmSelect.render({
            el: el,
            name: name,

            tree: {
                show: true,
                showLine: true,
                showFolderIcon:true,
                indent: 20,
                expandedKeys:false
            },
            height: 'auto',
            data: data,
            on: function ({ arr, change, isAdd }) {
                return this
            }
        })
    }


    function getRolesAllJson(jsons) {
        let tmpitem=[]
        for (let item of jsons) {
            let tmparr={}
            tmparr["value"]=item["code"];
            tmparr["name"]=item["name"];
            tmpitem.push(tmparr)
        }
        return tmpitem
    }

    function getRolesxmselect(el,name, data) {
        return xmSelect.render({
            el: el,
            name: name,
            paging: true,
            pageSize: 10,
            filterable: true,
            height: 'auto',
            data: data,
        })
    }


    //获取所有用户所管理的部门
    function getAllDepartmentUser() {
        let userTree = {};
        $.ajax({
            type: 'get',
            url: 'department/getAllDepartmentUser',
            dataType: "json",
            async: false,
            success: function (data) {
                if (data.status == 200) {
                    userTree = data.data;
                }
            },
            error: function (data) {
            }
        });
        return userTree;

    }

    layer.ready(function () {
        //所有部门
        let deptList=[];
        $.ajax({
            url:'department/getAllDept',
            success:function (data) {
                deptList = data.data;
                for(let i in deptList){
                    $('#departmentCode').append(new Option(deptList[i].name, deptList[i].code));
                }
                for(let i in deptList){
                    if (userDepartmentCode==deptList[i].code){
                        $('#departmentCode').val(deptList[i].code);
                        break;
                    }
                }
                form.render('select');
            }
        })

    });
var roleDatas=[];//角色列表
    var roles_curr="";//当前用户的角色值
   // selectMultip.register();
   if(topbase=="top"){
        $('#userUpdate-form').find('input,textarea,select').attr('disabled',true);
        $('#userUpdate-form').find('button').attr('display','none');
        //$("#tj").style("display","none")
       $("#tj").css("display","none");
    }
    //获取所有角色
    getRoles();

    laydate.render({
        elem: '#birthday'
    });
    if(dcode !="") {
        $("span")[0].innerHTML="新增用户";

        $('#logRow').hide()
        getSelectInfo();
    }else{
        decode="0";
    }
    if(usercode !=""){
        $("span")[0].innerHTML="编辑用户";
        getEditInit();
       data.birthday=dateformat(data.birthday);

        form.val("userUpdate-form",{
            "sex":data.sex,
            // "roles":data.roles,
            "birthday":data.birthday,
            "msn":data.msn
        })
        roles_curr=data.roles;
        getrolenamebyrolecode();
        laydate.render({
            elem: '#birthday'

        });
        form.render();//表单刷新
    }
//根据角色code获取角色名称
    function getrolenamebyrolecode(){
        if(roles_curr==null){
            if( $("input[name='roles2']").length >0){
                $("input[name='roles2']")[0].value="";
            }

            return;
        }
        var roles=roles_curr.split(",");
        var rolename="";
        for(var i=0;i<roles.length;i++){//roleDatas
            var role=roles[i];
            for (var n=0;n<roleDatas.length;n++){
                var m=roleDatas[n];
                if(role==m.code){
                    rolename+=m.name+",";
                    break;
                }
            }
        }
        rolename=rolename.substr(0,rolename.length-1);
        if($("input[name='roles2']").length >0){
            $("input[name='roles2']")[0].value=rolename;
        }

    }

    //头像
    upload.render({
        elem: '#headingadd'
        , url: 'ftp/uploadFile'
        , field: "uploadify"     //添加这个属性与后台名称保存一致
        , accept: 'file' //允许上传的文件类型
        ,data:{"fileType":"heading"}//头像
        ,before: function(obj) {
            /*var thin = this;
            obj.preview(function(index, file, result){
                $("#"+thin.id+"").attr('src', result); //图片链接（base64）
            });*/

        }
        ,done: function(res){
            //如果上传失败
            if(res.status !=200){
                return layer.msg('上传失败');
            }else{
                var ftpPath=res.data[0].ftpPath;
                var fileName=res.data[0].fileName;
                var src=getFtpPath(ftpPath,fileName);
                $("#headimg").attr('src',src);
                $("input[name='headimg']")[0].value=src;
            }
            //上传成功
        }
        ,error: function(){
            layer.msg('上传失败,请稍后重试')
        }
    })
    //英文签章
    upload.render({
        elem: '#englishSealUrladd'
        , url: 'ftp/uploadFile'
        , field: "uploadify"     //添加这个属性与后台名称保存一致
        , accept: 'file' //允许上传的文件类型
        ,data:{"fileType":"englishSealUrl"}//头像
        ,before: function(obj) {
            /*var thin = this;
            obj.preview(function(index, file, result){
                $("#"+thin.id+"").attr('src', result); //图片链接（base64）
            });*/

        }
        ,done: function(res){
            //如果上传失败
            if(res.status !=200){
                return layer.msg('上传失败');
            }else{
                var ftpPath=res.data[0].ftpPath;
                var fileName=res.data[0].fileName;
                 var src=getFtpPath(ftpPath,fileName);
                $("#englishSealUrl").attr('src',src);
                $("input[name='englishSealUrl']")[0].value=src;

            }
            //上传成功
        }
        ,error: function(){
            layer.msg('上传失败,请稍后重试')
        }
    })
    //中文签章
    upload.render({
        elem: '#chinaSealUrladd'
        , url: 'ftp/uploadFile'
        , field: "uploadify"     //添加这个属性与后台名称保存一致
        , accept: 'file' //允许上传的文件类型
        ,data:{"fileType":"chinaSealUrl"}//头像
        ,before: function(obj) {
            /*var thin = this;
            obj.preview(function(index, file, result){
                $("#"+thin.id+"").attr('src', result); //图片链接（base64）
            });*/

        }
        ,done: function(res){
            //如果上传失败
            if(res.status !=200){
                return layer.msg('上传失败');
            }else{
                var ftpPath=res.data[0].ftpPath;
                var fileName=res.data[0].fileName;
                var src=getFtpPath(ftpPath,fileName);
                $("#chinaSealUrl").attr('src',src);
                $("input[name='chinaSealUrl']")[0].value=src;

            }
            //上传成功
        }
        ,error: function(){
            layer.msg('上传失败,请稍后重试')
        }
    })
    //角色文本框点击事件
    $("#roles2").on("click",function (obj) {
        ids.length=0;
        tableIds.length=0;
       // roleDatas=[];
       // getRoles();
        layer.open({
            type: 1,
            title: "角色",
            area: ['710px', '420px'],
            content: $("#erelevance")//引用的弹出层的页面层的方式加载修改界面表单
        });
        table.render({
            elem: '#erelevanceid'
            ,data:roleDatas
            ,cols: [[
                {checkbox: true, sort : true,title:'选择'},

                ,{field:'code', title:'编码', fixed: true}
                ,{field:'name', title:'角色组/角色'}
            ]]
            ,id: 'erelevancetableid'
            ,page: true
            ,done:function (res) {
               /* //所有复选框取消选择
                $('.layui-table-header th[data-field="0"] input[type="checkbox"]').prop('checked', false);
                form.render('checkbox'); //刷新checkbox选择框渲染*/

                // 设置当前页全部数据id到全局变量
                tableIds = res.data.map(function (value) {
                    return value.code;
                });
                // 设置当前页选中项
                $.each(res.data, function (idx, val) {

                    if (roles_curr.indexOf(val.code) > -1) {
                        ids.push(val.code);
                        val["LAY_CHECKED"] = 'true';
                        //找到对应数据改变勾选样式，呈现出选中效果
                        let index = val['LAY_TABLE_INDEX'];
                        $('tr[data-index=' + index + '] input[type="checkbox"]').click();
                        form.render('checkbox'); //刷新checkbox选择框渲染
                    }
                });
                // 获取表格勾选状态，全选中时设置全选框选中
               /* let checkStatus = table.checkStatus('erelevancetableid');
                if (checkStatus.isAll) {
                    $('.layui-table-header th[data-field="0"] input[type="checkbox"]').prop('checked', true);
                    form.render('checkbox'); //刷新checkbox选择框渲染
                }*/
            }
        });

    })

    // 监听勾选事件
    table.on('checkbox(erelevanceid)', function (obj) {

        if (obj.checked == true) {
            if (obj.type == 'one') {
                ids.push(obj.data.code);
            } else {
              //var checkData=  table.checkStatus('erelevancetableid').data;
                for (let i = 0; i < tableIds.length; i++) {
                    //当全选之前选中了部分行进行判断，避免重复
                    if (ids.indexOf(tableIds[i] ) == -1) {
                        ids.push(tableIds[i] );
                    }
                }
            }
        } else {
            if (obj.type == 'one') {
                let i = ids.length;
                while (i--) {
                    if (ids[i] == obj.data.code) {
                        ids.splice(i, 1);
                    }
                }
            } else {
                let i = ids.length;
                while (i--) {
                    if (tableIds.indexOf(ids[i]) != -1) {
                        ids.splice(i, 1);
                    }
                }
            }
        }
    });


    //角色选择后提交
    $("#erelevancetj").on('click',function () {
       /* var roless="";
        //var rolessets=[];
        var checkeds = $("input[name='rolecheckbox']");

        for(var i=0;i<checkdata.length;i++){
            if(checkeds[i].checked==true){
              //  rolessets.push(checkeds[i].value);
                roless+=checkeds[i].value+",";
            }
        }*/
        roles_curr=ids.join(",");
        getrolenamebyrolecode();
        $("#roles")[0].value=roles_curr;//roless.substr(0,roless.length-1);
        form.render();
        layer.closeAll();
        //表单刷新
      /*  if(updateAccount(checkeds,associatedname,associatedid)){
            layer.msg("关联成功！");
            layer.closeAll();
            searchs();
        }else{
            layer.msg("关联失败！");
        }*/

        /*layer.closeAll();
        layer.msg("关联用户ID"+associatedid+'选中了账号：ID为'+ checkeds);*/
    })
    //头像删除
    $("#headimgdel").on('click',function () {
        $("#headimg").attr('src','');
       // headimg = "";
        $("input[name='headimg']")[0].value="";
    })
    //签章删除
    $("#englishSealUrldel").on('click',function (){
        $("#englishSealUrl").attr('src','');
      //  englishSealUrl="";
        $("input[name='englishSealUrl']")[0].value="";
    })
    $("#chinaSealUrldel").on('click',function (){
        $("#chinaSealUrl").attr('src','');
       // chinaSealUrl="";
        $("input[name='chinaSealUrl']")[0].value="";
    })
    //监听提交
    form.on('submit(user-form-element)', function(data){
      if(usercode !=""){//更新
          var num=update(data);
          if(num < 10000 && num > 0){
              layer.msg("更新成功", {icon: 6});
              refresh2();
          }else if (num < 10000 && num == 0){
              layer.msg("本地更新失败", {icon: 6});
          }else if (num >10000){
              layer.msg("同步云枢更新失败", {icon: 6});
          }
         /* if(){
              layer.msg("更新成功", {icon: 6});
              refresh2();
          }else{
              layer.msg("更新失败", {icon: 6});
          }*/
      }else{
          //data.field为表单元素所有数据
          var num=insert(data)
          if(num < 10000 && num > 0){
              layer.msg("保存成功", {icon: 6});
              refresh2();
          }else if (num < 10000 && num == 0){
              layer.msg("本地保存失败", {icon: 6});
          }else if (nu >10000){
              layer.msg("同步云枢保存失败", {icon: 6});
          }
         /* if(num < 10000 && num >0){
              layer.msg("删除成功!");
          }else if(num <10000 && num ==0){
              layer.msg("本地删除失败!");

          }else if(num >10000){
              layer.msg("同步云枢删除失败!");

          }*/
      }

        return false;
    });

    //---操作日志
    table.render({
        elem: '#userLog'
        , data: logDBList
        , cols: [[
            {field: 'operationType', title: '操作类型',width: 120}
            , {field: 'operatorName', title: '操作员',width: 120}
            , {field: 'operationDate', title: '操作日期',width: 120}
            , {field: 'modifyContent', title: '修改内容'}
        ]]
        , id: 'logtableid'
        , height: 380
        , limit: 50//显示的数量
        , page: true
    });







function dateformat(cur){
    let date = new Date(cur);
    let year = date.getFullYear();
    let month = date.getMonth()+1;
    let day = date.getDate();
    month = month < 10 ? "0"+month:month;
    day = day < 10 ? "0"+day:day;
    return  year+'-'+month+'-'+day;
}
function  refresh2() {
    setTimeout(function () {
        //保存成功则刷新提交过来的界面 并关闭此页面
       // parent.detab("views/jsp/SystemCenter/usersettings.jsp");
        //parent.intab("views/jsp/SystemCenter/usersettings.jsp","用户设置")
        if(dcode !=""){
            parent.detab("views/jsp/SystemCenter/tpl/newupuser.jsp?dcode="+dcode);
        }   else{
            parent.detab("views/jsp/SystemCenter/tpl/newupuser.jsp?usercode="+data.code);
           /* parent.detab("views/jsp/SystemCenter/tpl/newupuser.jsp"+(userid==''?'':'?userid='+userid));*/
        }


    },1000)
    return false;
}
function  refresh() {
    setTimeout(function () {
        //保存成功则刷新提交过来的界面 并关闭此页面
        parent.detab("views/jsp/SystemCenter/usersettings.jsp");
        parent.intab("views/jsp/SystemCenter/usersettings.jsp","用户设置")
        if(dcode !=""){
            parent.detab("views/jsp/SystemCenter/tpl/newupuser.jsp?dcode="+dcode);
        }   else{
            parent.detab("views/jsp/SystemCenter/tpl/newupuser.jsp"+(userid==''?'':'?userid='+userid));
        }


    },1000)
    return false;
}
function  update(data) {
    data.field.id=userid;
    data.field.roles=data.field.rolesCode;
var tf=false;
    $.ajax({
        type : 'POST',
        //  url : 'resource/getTree',
        data:JSON.stringify(data.field),
        url:'user/updateByKey',
        dataType:"json",
        contentType: 'application/json',
        async:false,
        success : function (da) {
            if(da.status==200 ){
                //tf=true;
                tf=da.data;
            }
        },
        error: function(data) {
            layer.msg("更新失败!");
        }
    });
    return tf;
}
function  insert(data) {
    var tf=false;
    data.field.departmentCode=dcode;
    data.field.roles=data.field.rolesCode;
    $.ajax({
        type : 'POST',
        //  url : 'resource/getTree',
        data:JSON.stringify(data.field),
        url:'user/insert',
        dataType:"json",
         contentType: 'application/json',
        async:false,
        success : function (da) {
            if(da.status==200 ){
                //tf=true;
                tf=da.data;
            }
        },
        error: function(data) {
            layer.msg("保存失败!");
        }
    });
    return tf;
}
function getUserByid() {
    var tf=false;
    $.ajax({
        type : 'POST',
        //  url : 'resource/getTree',
        data:{"code":usercode},
        url:'user/selectByCode',
        dataType:"json",
    // contentType: 'application/json',
    async:false,
        success : function (da) {
        if(da.status==200 ){
            tf=true;
            data=da.data.user;
            userDepartmentCode=da.data.user.departmentCode;
            logDBList=da.data.userLogList;
        }
    },
    error: function(data) {
        layer.msg("初始化失败!");
    }
    });
    return tf;
}
function getEditInit() {
    //取值
     if(!getUserByid()){

     }
    //赋值
    userid=data.id;
    $("input[name='name']")[0].value=data.name;
    $("input[name='englishName']")[0].value=data.englishName;
    $("input[name='code']")[0].value=data.code;
    $("input[name=code]")[0].readOnly=true;

    $("input[name='email']")[0].value=data.email;
    $("input[name='address']")[0].value=data.address;
    $("input[name='telephone']")[0].value=data.telephone;
    $("input[name='phone']")[0].value=data.phone;
    $("input[name='qq']")[0].value=data.qq;
    //$("input[name='msn']")[0].value=data.msn;
    $("input[name='skype']")[0].value=data.skype;
    $("input[name='ww']")[0].value=data.ww;
    $("input[name='chinaSealUrl']")[0].value=data.chinaSealUrl;
    $("#chinaSealUrl").attr("src",data.chinaSealUrl);
    $("input[name='englishSealUrl']")[0].value=data.englishSealUrl;
    $("#englishSealUrl").attr("src",data.englishSealUrl);
    $("textarea[name='desc']")[0].value=data.desc;
   // $("input[name='desc']")[0].value=data.desc;
    $("input[name='headimg']")[0].value=data.headimg;
    $("#headimg").attr("src",data.headimg);

    //管理组
    let customerRole = data["customerRole"];
    if(!isEmpty(customerRole)){
        userRoleList = customerRole.split(",");
    }
    getSelectInfo();
    let roleArray=data.roles.split(",");

    rolesTreeList.setValue(roleArray);
}

//字符串val是否在数据arr中(true:在 false:不在)
function checkIsContain(arr, val) {
    if(arr.indexOf(val) > -1){
        return true;
    }else {
        return false;
    }
}

function getSelectInfo() {
    let userList = getAllDepartmentUser();
    if(userList && userList.list){
        let userTree = getAllJson(userList.list);
        getxmselect("#customerRole","customerRole", userTree)
    }else {
        getxmselect("#customerRole","customerRole", [{name: user.name, value: user.code}])
    }

    let roleTree=getRolesAllJson(roleDatas);
    rolesTreeList=getRolesxmselect("#rolesCode","rolesCode", roleTree)
}
function getRoles() {
    $.ajax({
        type : 'GET',
        //  url : 'resource/getTree',
        url:'role/selectAll',
        dataType:"json",
       // contentType: 'application/json',
        async:false,
        success : function (da) {
            if(da.status==200 ){
                roleDatas=da.data;

               /* var data = []
                for(var i = 0;i < datas.length;i++){
                    var obj ={};
                    obj.value=datas[i].code;
                    obj.text=datas[i].name;
                    data.push(obj);
                }
                selectMultip.reload("roles", data);*/
            }
        },
        error: function(data) {
            layer.msg("初始化失败!");
        }
    });
}

//字段是否为空或者零
function isEmpty(obj){
    if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
        return true;
    }else{
        return false;
    }
}